package com.mokio.controller;

import com.mokio.entity.Users;
import com.mokio.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: xiaomishop
 * @ClassName UserController
 * @description:
 * @author: mokio
 * @create: 2024−12-10 20:59
 * @Version 1.0
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * @param username
     * @param password
     * @param session
     * @return
     */

    @RequestMapping("/login.action")
    public String login(@RequestParam("uname") String username, @RequestParam("upass") String password, String yzm,HttpSession session) {

        String yzmR = (String) session.getAttribute("random");
        if (!yzm.equals(yzmR)){
            session.setAttribute("msg","验证码输入错误!");
            return "redirect:/login.jsp";
        }


        Map<String, Object> map = userService.login(username, password);
        if("ok".equals(map.get("s"))){
            //登录成功了
            session.setAttribute("user",map.get("user"));
            return "redirect:/main.jsp";

        }else{

            session.setAttribute("msg","登录失败!");
            return "redirect:/login.jsp";
        }
    }
    //  /user/register.action
    @RequestMapping("/register.action")
    @ResponseBody
    public Map<String, Object> register(@RequestParam("uname") String username, @RequestParam("upass") String password, HttpSession session) {
        Users userByName = userService.findUserByName(username);
        Map<String, Object> result = new HashMap<>();
        // 检查用户名是否已存在
        if (userByName != null){
            result.put("status", "fail");
            result.put("message", "用户名已存在");
            return result;
        }
        // 注册新用户
        Users newUser = new Users();
        newUser.setUname(username);
        newUser.setUpass(password);
        userService.saveUser(newUser);

        // 将用户信息存入Session
        newUser = userService.findUserByName(username);
        session.setAttribute("user", newUser);

        // 返回成功结果
        result.put("status", "true");
        result.put("message", "注册成功");
        return result;

    }
}
